package com.tianma315.core.common.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.tianma315.core.common.domain.ConfigDO;
import com.tianma315.core.common.service.ConfigService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;


@Component
public class WechatMpConfig {

	@Autowired
    private ConfigService configService;

    @Bean
    public WxMpService wxMpService() {
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxMpConfigStorage());
        return wxMpService;
    }

    @Bean
    public WxMpConfigStorage wxMpConfigStorage() {
        WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl();
        ConfigDO configDO  = configService.getByKey("wx_config");
        String v = configDO.getV();
        JSONObject json = JSON.parseObject(v);
        String appid = (String) json.get("appid");
        String appsecret = (String) json.get("appsecret");
        config.setAppId(appid);
        config.setSecret(appsecret);
        return config;
    }
}
